# 9.2 Cron4jPlugin

# 1. Basic Configuration

Cron4jPlugin exists as a plugin for JFinal, so it needs to be configured in JFinalConfig. Below is an example code snippet:

Cron4jPlugin cp = new Cron4jPlugin();
cp.addTask("* * * * *", new MyTask());
me.add(cp);
1
2
3

As shown above, creating the plugin, passing parameters to addTask, and adding it to JFinal completes the basic configuration. The first parameter of cp.addTask is the cron expression for task scheduling, and the second parameter is an implementation of the Runnable interface. Cron4jPlugin will invoke the run method in MyTask according to the cron expression.

In the above example, besides using a Runnable implementation for MyTask, you can also use an implementation of the ITask interface. This interface has a stop() method that will be called back when scheduling stops.

# 2. Cron Expressions

Cron expressions are used to customize scheduling rules. Unlike Quartz's cron expression, Cron4jPlugin's cron expression allows up to five parts, each separated by a space. These five parts represent minute, hour, day, month, and week, respectively, and have the following rules:

  • Minute: from 0 to 59
  • Hour: from 0 to 23
  • Day: from 1 to 31, the letter 'L' can represent the last day of the month
  • Month: from 1 to 12, can use aliases like "jan", "feb", "mar", etc.
  • Week: from 0 to 6, where 0 represents Sunday and 6 represents Saturday, can use aliases like "sun", "mon", "tue", etc.

These five parts support various characters, including:

  • Number ( n ): Represents a specific time point, e.g., 5 * * * * means to execute at the 5th minute.
  • Comma ( , ): Specifies multiple values, e.g., 3,5 * * * * means to execute at the 3rd and 5th minutes.
  • Hyphen ( - ): Indicates a range, e.g., 1-3 * * * * means to execute at the 1st, 2nd, and 3rd minutes.
  • Asterisk ( * ): Means every time point, e.g., * * * * * means to execute every minute.
  • Slash ( / ): Specifies an increment value, e.g., */5 means to execute every 5 minutes.

# Common Mistakes:

The use of the slash character in cron4j differs slightly from Linux. For example, the expression 10/3 * * * * in Linux means to schedule every three minutes starting from the 10th minute, while in cron4j, you need to use 10-59/3 * * * *.

# Frequently Asked Questions:

  1. If a task throws an exception, will it be scheduled again at its next scheduled time? The answer is yes.
  2. If a task takes a long time to execute and hasn't finished by the time it's scheduled again, will it still be scheduled? The answer is also yes.

In summary, each scheduling is independent; whether the last scheduling threw an exception or finished has no impact on the current scheduling.

# Special Reminder:

Cron4jPlugin's cron expression, like Linux's, only has five parts, unlike Quartz's seven parts. Any 7-part cron expressions found online should not be used with Cron4jPlugin.

Last Updated: 9/22/2023, 7:21:10 AM